<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>题目管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增题目
            </el-button>
            <el-button type="success" @click="handleImport">
              <el-icon><Upload /></el-icon>
              导入题目
            </el-button>
            <el-button type="info" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出题目
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="题目内容" prop="content">
            <el-input
              v-model="queryParams.content"
              placeholder="请输入题目内容"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="题目类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择题目类型" clearable style="width: 150px">
              <el-option label="单选题" value="SINGLE_CHOICE" />
              <el-option label="多选题" value="MULTIPLE_CHOICE" />
              <el-option label="判断题" value="TRUE_FALSE" />
              <el-option label="填空题" value="FILL_BLANK" />
              <el-option label="简答题" value="SHORT_ANSWER" />
              <el-option label="编程题" value="CODING" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度等级" prop="difficulty">
            <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable style="width: 120px">
              <el-option label="简单" value="EASY" />
              <el-option label="中等" value="MEDIUM" />
              <el-option label="困难" value="HARD" />
            </el-select>
          </el-form-item>
          <el-form-item label="科目分类" prop="categoryId">
            <el-select v-model="queryParams.categoryId" placeholder="请选择科目" clearable style="width: 150px">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目ID" align="center" prop="id" width="80" />
        <el-table-column label="题目内容" align="left" prop="content" :show-overflow-tooltip="true" min-width="300">
          <template #default="scope">
            <div class="question-content">
              <div class="content-text">{{ scope.row.content }}</div>
              <div v-if="scope.row.type === 'SINGLE_CHOICE' || scope.row.type === 'MULTIPLE_CHOICE'" class="options">
                <div v-for="(option, index) in scope.row.options" :key="index" class="option-item">
                  {{ String.fromCharCode(65 + index) }}. {{ option.content }}
                  <el-tag v-if="option.isCorrect" type="success" size="small">正确答案</el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="题目类型" align="center" prop="type" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="难度等级" align="center" prop="difficulty" width="100">
          <template #default="scope">
            <el-tag :type="getDifficultyTagType(scope.row.difficulty)">
              {{ getDifficultyText(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" prop="score" width="80" />
        <el-table-column label="科目分类" align="center" prop="categoryName" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" icon="View" @click="handleDetail(scope.row)" link>查看</el-button>
            <el-button type="primary" icon="Edit" @click="handleUpdate(scope.row)" link>修改</el-button>
            <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="题目类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择题目类型" style="width: 100%" @change="handleTypeChange">
                <el-option label="单选题" value="SINGLE_CHOICE" />
                <el-option label="多选题" value="MULTIPLE_CHOICE" />
                <el-option label="判断题" value="TRUE_FALSE" />
                <el-option label="填空题" value="FILL_BLANK" />
                <el-option label="简答题" value="SHORT_ANSWER" />
                <el-option label="编程题" value="CODING" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度等级" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度" style="width: 100%">
                <el-option label="简单" value="EASY" />
                <el-option label="中等" value="MEDIUM" />
                <el-option label="困难" value="HARD" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科目分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择科目" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分值" prop="score">
              <el-input-number v-model="form.score" :min="1" :max="100" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入题目内容"
          />
        </el-form-item>

        <!-- 选择题选项 -->
        <div v-if="form.type === 'SINGLE_CHOICE' || form.type === 'MULTIPLE_CHOICE'">
          <el-form-item label="选项设置">
            <div class="options-container">
              <div v-for="(option, index) in form.options" :key="index" class="option-row">
                <el-input
                  v-model="option.content"
                  :placeholder="`选项 ${String.fromCharCode(65 + index)}`"
                  style="flex: 1; margin-right: 10px;"
                />
                <el-checkbox
                  v-if="form.type === 'MULTIPLE_CHOICE'"
                  v-model="option.isCorrect"
                  style="margin-right: 10px;"
                >
                  正确答案
                </el-checkbox>
                <el-radio
                  v-if="form.type === 'SINGLE_CHOICE'"
                  v-model="correctAnswerIndex"
                  :label="index"
                  style="margin-right: 10px;"
                >
                  正确答案
                </el-radio>
                <el-button type="danger" size="small" @click="removeOption(index)" :disabled="form.options.length <= 2">
                  删除
                </el-button>
              </div>
              <el-button type="primary" size="small" @click="addOption" style="margin-top: 10px;">
                添加选项
              </el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 判断题答案 -->
        <div v-if="form.type === 'TRUE_FALSE'">
          <el-form-item label="正确答案" prop="answer">
            <el-radio-group v-model="form.answer">
              <el-radio label="true">正确</el-radio>
              <el-radio label="false">错误</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 填空题/简答题/编程题答案 -->
        <div v-if="['FILL_BLANK', 'SHORT_ANSWER', 'CODING'].includes(form.type)">
          <el-form-item label="参考答案" prop="answer">
            <el-input
              v-model="form.answer"
              type="textarea"
              :rows="4"
              placeholder="请输入参考答案"
            />
          </el-form-item>
        </div>

        <el-form-item label="解析说明">
          <el-input
            v-model="form.explanation"
            type="textarea"
            :rows="3"
            placeholder="请输入题目解析（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, Search, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref('')
const open = ref(false)
const queryRef = ref()
const questionRef = ref()
const correctAnswerIndex = ref(0)

// 列表数据
const questionList = ref([])
const categories = ref([
  { id: 1, name: '数学' },
  { id: 2, name: '语文' },
  { id: 3, name: '英语' },
  { id: 4, name: '物理' },
  { id: 5, name: '化学' },
  { id: 6, name: '计算机科学' }
])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  content: undefined,
  type: undefined,
  difficulty: undefined,
  categoryId: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  content: '',
  type: 'SINGLE_CHOICE',
  difficulty: 'MEDIUM',
  categoryId: undefined,
  score: 5,
  answer: '',
  explanation: '',
  options: [
    { content: '', isCorrect: false },
    { content: '', isCorrect: false }
  ]
})

// 表单验证规则
const rules = reactive({
  content: [
    { required: true, message: '题目内容不能为空', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择科目分类', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' }
  ]
})

// 获取题目列表
const getList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    const mockData = {
      code: 200,
      data: {
        total: 25,
        rows: [
          {
            id: 1,
            content: '以下哪个是JavaScript的数据类型？',
            type: 'SINGLE_CHOICE',
            difficulty: 'EASY',
            categoryId: 6,
            categoryName: '计算机科学',
            score: 5,
            answer: '0',
            explanation: 'JavaScript有七种基本数据类型：number、string、boolean、null、undefined、symbol、bigint',
            options: [
              { content: 'string', isCorrect: true },
              { content: 'integer', isCorrect: false },
              { content: 'float', isCorrect: false },
              { content: 'char', isCorrect: false }
            ],
            createTime: '2024-01-15 10:30:00'
          },
          {
            id: 2,
            content: '请选择所有正确的HTML5语义化标签：',
            type: 'MULTIPLE_CHOICE',
            difficulty: 'MEDIUM',
            categoryId: 6,
            categoryName: '计算机科学',
            score: 8,
            answer: '0,2,3',
            explanation: 'HTML5引入了许多语义化标签来更好地描述文档结构',
            options: [
              { content: '<header>', isCorrect: true },
              { content: '<div>', isCorrect: false },
              { content: '<nav>', isCorrect: true },
              { content: '<section>', isCorrect: true }
            ],
            createTime: '2024-01-15 11:20:00'
          },
          {
            id: 3,
            content: 'CSS中的盒模型包括内容、内边距、边框和外边距。',
            type: 'TRUE_FALSE',
            difficulty: 'EASY',
            categoryId: 6,
            categoryName: '计算机科学',
            score: 3,
            answer: 'true',
            explanation: 'CSS盒模型确实包括这四个部分：content、padding、border、margin',
            createTime: '2024-01-15 14:15:00'
          }
        ]
      }
    }

    questionList.value = mockData.data.rows
    total.value = mockData.data.total
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加题目'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const questionId = row.id || ids.value[0]
  // 模拟获取题目详情
  Object.assign(form, row)
  if (form.type === 'SINGLE_CHOICE') {
    // 找到正确答案的索引
    correctAnswerIndex.value = form.options.findIndex(option => option.isCorrect)
  }
  open.value = true
  title.value = '修改题目'
}

// 查看详情操作
const handleDetail = (row) => {
  ElMessage.info('查看题目详情功能开发中')
}

// 删除按钮操作
const handleDelete = async (row) => {
  const questionIds = row.id || ids.value
  try {
    await ElMessageBox.confirm('是否确认删除题目编号为"' + questionIds + '"的数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 模拟删除API调用
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 导入按钮操作
const handleImport = () => {
  ElMessage.info('题目导入功能开发中')
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('题目导出功能开发中')
}

// 题目类型改变处理
const handleTypeChange = (type) => {
  if (type === 'SINGLE_CHOICE' || type === 'MULTIPLE_CHOICE') {
    if (form.options.length === 0) {
      form.options = [
        { content: '', isCorrect: false },
        { content: '', isCorrect: false }
      ]
    }
  } else {
    form.options = []
  }
  form.answer = ''
  correctAnswerIndex.value = 0
}

// 添加选项
const addOption = () => {
  form.options.push({ content: '', isCorrect: false })
}

// 删除选项
const removeOption = (index) => {
  form.options.splice(index, 1)
  if (correctAnswerIndex.value >= index && correctAnswerIndex.value > 0) {
    correctAnswerIndex.value--
  }
}

// 提交表单
const submitForm = () => {
  questionRef.value?.validate(async (valid) => {
    if (valid) {
      // 处理单选题正确答案
      if (form.type === 'SINGLE_CHOICE') {
        form.options.forEach((option, index) => {
          option.isCorrect = index === correctAnswerIndex.value
        })
        form.answer = correctAnswerIndex.value.toString()
      }

      // 处理多选题正确答案
      if (form.type === 'MULTIPLE_CHOICE') {
        const correctIndexes = form.options
          .map((option, index) => option.isCorrect ? index : -1)
          .filter(index => index !== -1)
        form.answer = correctIndexes.join(',')
      }

      try {
        if (form.id) {
          // 模拟更新API调用
          ElMessage.success('修改成功')
        } else {
          // 模拟新增API调用
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    content: '',
    type: 'SINGLE_CHOICE',
    difficulty: 'MEDIUM',
    categoryId: undefined,
    score: 5,
    answer: '',
    explanation: '',
    options: [
      { content: '', isCorrect: false },
      { content: '', isCorrect: false }
    ]
  })
  correctAnswerIndex.value = 0
  questionRef.value?.resetFields()
}

// 工具函数
const getTypeText = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'CODING': '编程题'
  }
  return typeMap[type] || '未知'
}

const getTypeTagType = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': 'primary',
    'MULTIPLE_CHOICE': 'success',
    'TRUE_FALSE': 'warning',
    'FILL_BLANK': 'info',
    'SHORT_ANSWER': 'danger',
    'CODING': 'primary'
  }
  return typeMap[type] || 'info'
}

const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难'
  }
  return difficultyMap[difficulty] || '未知'
}

const getDifficultyTagType = (difficulty) => {
  const typeMap = {
    'EASY': 'success',
    'MEDIUM': 'warning',
    'HARD': 'danger'
  }
  return typeMap[difficulty] || 'info'
}

const parseTime = (time, pattern) => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getList()
})
</script>
